import * as source from '../src/index';

const loading = document.getElementById('loading');
const resCanvas = document.getElementById('resCanvas') as HTMLCanvasElement;
const resCtx = resCanvas.getContext('2d') as CanvasRenderingContext2D;
const fileReader = new FileReader();

// 初始化模型
load();

document.getElementById('uploadImg')!.onchange = function () {
    loadFile(this);
};

async function load() {
    await source.init();
    loading.style.display = 'none';

}

async function run(imgPath: string) {
    loading.style.display = 'block';
    const imgElement = await source.createImage(imgPath);
    drawImage(imgElement);

    // 得到blazeface人脸框结果
    const res_detect = await source.detect(imgPath);
    // 绘制blazeface预测结果
    drawDecResult(res_detect);
    // 将blazeface绘制图像保存，用于标记关键点
    let imgsrc = resCanvas.toDataURL("../imgs/temp.png") ;
    // 得到landmark标记结果
    const res_landmark = await source.keyPointDetection(imgsrc);
    // 绘制landmark标记结果
    drawMarkResult(res_landmark);
    loading.style.display = 'none';
}

async function loadFile(ipt) {
    if (!ipt.files || !ipt.files[0]) {
        return;
    }
    fileReader.onload = function (evt) {
        if (evt.target && typeof evt.target.result === 'string') {
            run(evt.target.result);
        }
    };
    fileReader.readAsDataURL(ipt.files[0]);
}

// 绘图
function drawImage(img: HTMLImageElement) {
    const naturalWidth = 640;
    const naturalHeight = 640;
    resCanvas.width = naturalWidth;
    resCanvas.height = naturalHeight;
    resCtx.drawImage(img, 0, 0, naturalWidth, naturalHeight);
}

// 识别结果
function drawDecResult(data) {
    resCtx.fillStyle = resCtx.strokeStyle = 'Red';
    resCtx.font = '20px';
    resCtx.lineWidth = 2;
    data.forEach(item => {
        const x = item.left * resCanvas.width;
        const y = item.top * resCanvas.height;
        const w = item.width * resCanvas.width;
        const h = item.height * resCanvas.height;
        resCtx.strokeRect(x, y, w, h);
        resCtx.fillText(item.confidence.toFixed(6), x, y);
    });
}

// 关键点结果
function drawMarkResult(data) {
    resCtx.fillStyle = resCtx.strokeStyle = 'Green';
    resCtx.font = '10px';
    resCtx.lineWidth = 0.5;
    data.forEach(item => {
        const x = item.left * resCanvas.width;
        const y = item.top * resCanvas.height;
        const w = item.width * resCanvas.width;
        const h = item.height * resCanvas.height;
        resCtx.strokeRect(x, y, w, h);
        resCtx.fillText(item.confidence.toFixed(6), x, y);
    });
}